package com.sniff.atp.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.sniff.atp.constant.LoginConstant;
import com.sniff.atp.dto.ClientLoginDTO;
import com.sniff.atp.dto.ContentDTO;
import com.sniff.atp.dto.SystemLoginDTO;
import com.sniff.atp.dto.WMSLoginDTO;
import com.sniff.atp.dto.request.CreateOrderDTO;
import com.sniff.atp.dto.request.OrderProductDTO;
import com.sniff.atp.dto.request.StockOutDTO;
import com.sniff.atp.dto.response.CreateOrderResponse;
import com.sniff.atp.entity.ToolsInfo;
import com.sniff.atp.enums.status.CustomerOperateType;
import com.sniff.atp.enums.status.OrderType;
import com.sniff.atp.enums.status.PurchaseAbnormalType;
import com.sniff.atp.manager.ToolsInfoMananager;
import com.sniff.atp.response.SniffResponse;
import com.sniff.atp.service.login.ClientLoginService;
import com.sniff.atp.service.order.AbnormalOrderService;
import com.sniff.atp.service.order.MixtureOrderService;
import com.sniff.atp.service.order.OrderService;
import com.sniff.atp.service.order.PurchaseAllotOrder;
import com.sniff.atp.service.purchase.OEMPurchaseService;
import com.sniff.atp.service.purchase.PurchaseAbnormalService;
import com.sniff.atp.service.purchase.PurchaseService;
import com.sniff.atp.service.wms.storage.WMSCombinationOperationService;
import com.sniff.atp.service.wms.storage.WMSStorageService;
import com.sniff.atp.utils.*;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @BelongsProject: sniff-atp
 * @BelongsPackage: com.sniff.atp.controller.order
 * @Author: zxy
 * @CreateTime: 2022-11-10 17:40
 * @Description: client: 创建订单
 * @Version: 1.0
 */
@Api(value = "订单模块", tags = "订单模块")
@RestController
@RequestMapping("/order")
public class OrderController{

    @Autowired
    private OrderService orderService;
    @Autowired
    private PurchaseAllotOrder purchaseAllotOrder;
    @Autowired
    private ClientLoginService clientLoginService;
    @Autowired
    private MixtureOrderService mixtureOrderService;
    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private OEMPurchaseService oemPurchaseService;
    @Autowired
    private WMSStorageService wmsStorageService;
    @Autowired
    private WMSCombinationOperationService wmsCombinationOperationService;
    @Autowired
    private ToolsInfoMananager toolsInfoMananager;
    @Autowired
    private PurchaseAbnormalService purchaseAbnormalService;
    @Autowired
    private AbnormalOrderService abnormalOrderService;

    @ApiOperation("一键创建订单")
    @PostMapping("/createOrder")
    public SniffResponse<JSONObject> createOrder(@RequestBody CreateOrderDTO createOrderDTO) {


        ToolsInfo toolsInfo = toolsInfoMananager.selectOne(3L);
        toolsInfo.setCount(toolsInfo.getCount() + 1);
        toolsInfoMananager.updateOne(toolsInfo);


        JSONObject stringObjectHashMap = new JSONObject();

        SystemLoginDTO systemLoginDTO = LoginConstant.systemLoginDTO;
        WMSLoginDTO wmsLoginDTO = LoginConstant.wmsLoginDTO;
        /**
         *  [
         *     {"productSku":"OEMGOODS22101001000014","quantity":"2","productType":"OEM"},
         *     {"productSku":"d84fb55e0b5b0accccc000c9d9e76093","quantity":"2","productType":"normal"},
         *     {"productSku":"41b783f0ed2b1d9afde00cf989ba7615","quantity":"2","productType":"normal"},
         *     {"productSku":"SET22081711000006","quantity":"5","productType":"combination"}
         *   ]
         */

        String username = createOrderDTO.getUserName();
        String password = createOrderDTO.getPassword();
        Integer platform = createOrderDTO.getPlatform();
        Integer orderType = createOrderDTO.getOrderType();
        Integer operationNode = createOrderDTO.getOperationNode();
        Boolean getUseOneTheWayInventory = createOrderDTO.getUseOneTheWayInventory();
        ToolsUtil.stringBuild("getUseOneTheWayInventory", getUseOneTheWayInventory);


        ClientLoginDTO clientLoginDTO = clientLoginService.login(username, password);

        //判断平台
        if (!clientLoginDTO.getSystemSource().equals(platform.toString())) {
            clientLoginService.changeLogin(clientLoginDTO);
        }
        //判断订单类型
        if (2 == platform) {
            orderType = OrderType.STOCK.getType();
        }

        List<OrderProductDTO> products = createOrderDTO.getProducts();
        JSONArray stock2B = new JSONArray();
        for (int i = 0; i < products.size(); i++) {
            JSONObject object = new JSONObject();
            OrderProductDTO orderProductDTO = products.get(i);
            Integer productType = orderProductDTO.getProductType();
            if (productType == 1) {
                object.put("productType", "normal");
            } else if (productType == 2) {
                object.put("productType", "OEM");
            } else {
                object.put("productType", "combination");
            }
            object.put("quantity", orderProductDTO.getQuantity());
            object.put("productSku", orderProductDTO.getProductSku());
            stock2B.add(object);
        }

        // 执行下单
        String mixtureCreateOrderProcess = mixtureOrderService.mixtureCreateOrderProcess(clientLoginDTO, stock2B, orderType);
        JSONObject object = JsonUtil.strToJSONObject(mixtureCreateOrderProcess);
        JSONObject data = object.getJSONArray("data").getJSONObject(0);
        CreateOrderResponse createOrderResponse = FastUtil.toBean(data, CreateOrderResponse.class);
        stringObjectHashMap.put("platformData", createOrderResponse);

        String platformOrderNo = createOrderResponse.getPlatformOrderNo();

        if (operationNode == null || operationNode == 0 || operationNode == 1) {
            return SniffResponse.pass(stringObjectHashMap);
        }

        ToolsUtil.sleep(5000);
        String s = purchaseService.allotAutoOrder(systemLoginDTO, platformOrderNo);
        if(2 == operationNode) {
            JSONObject jsonObject = JsonUtil.strToJSONObject(s);
            stringObjectHashMap.put("allotData", jsonObject.getJSONArray("data"));
            return SniffResponse.pass(stringObjectHashMap);
        }


        // 执行采购
        String result = purchaseAllotOrder.getPurchaseOrderNo(platformOrderNo);
        if (StringUtils.isEmpty(result)){

            purchaseService.allotAutoOrder(LoginConstant.systemLoginDTO, platformOrderNo);
            //这个调用xxljob，需要更换到powerjob，现在是用powerjob
//            purchaseAllotOrder.allotAutoOrder();
            result = purchaseAllotOrder.getPurchaseOrderNo(platformOrderNo);

            if (StringUtils.isEmpty(result)) {
                return SniffResponse.fail(10001, "没有查到对应的采购单号！！！");
            }
        }
        JSONObject purchaseData = JSON.parseObject(result);
        JSONArray purchaseNos = purchaseData.getJSONArray("purchaseNo");
        JSONArray purchaseInfos = new JSONArray();

        for (int i = 0; i < purchaseNos.size(); i++) {
            JSONObject purchaseInfo =  new JSONObject();
            String purchaseNo = purchaseNos.getString(i);
            purchaseInfo.put("purchaseNo", purchaseNo);
            if (purchaseNo.contains("DHCGD")) {
                oemPurchaseService.oemPurchaseProcess(systemLoginDTO, purchaseNo);
                Object logisticsNumber = ToolsUtil.getStringBuild("oemLogisticsNumber");
                purchaseInfo.put("logisticsNumber", logisticsNumber);
            }else{
                purchaseService.puchasePrecess(LoginConstant.systemLoginDTO, purchaseNo);
                Object logisticsNumber = ToolsUtil.getStringBuild("logisticsNumber");
                purchaseInfo.put("logisticsNumber", logisticsNumber);
            }
            purchaseInfos.add(purchaseInfo);
        }
        stringObjectHashMap.put("purchaseData", purchaseInfos);
        if (operationNode == 3) {
            return SniffResponse.pass(stringObjectHashMap);
        }

        // 执行入库
        wmsStorageService.storageProcess(LoginConstant.wmsLoginDTO, platformOrderNo);
        if (operationNode == 4) {
            return SniffResponse.pass(stringObjectHashMap);
        }


        // 组合商品执行组合完成
        wmsCombinationOperationService.platformOrderCombinationProcess(wmsLoginDTO, platformOrderNo);
        if (operationNode == 5) {
            return SniffResponse.pass(stringObjectHashMap);
        }


        StockOutDTO stockOutDTO = new StockOutDTO();
        stockOutDTO.setPlatformOrderNo(platformOrderNo);
        stockOutDTO.setPickType(2);
        stockOutDTO.setDeliverType(2);

        // 小包发货

        return SniffResponse.pass(stringObjectHashMap);
    }



    @ApiOperation("创建组合商品落单订单")
    @PostMapping("/combination/order")
    public SniffResponse<JSONObject> combinationOrderCreate(@RequestBody CreateOrderDTO createOrderDTO) {


        ToolsInfo toolsInfo = toolsInfoMananager.selectOne(3L);
        toolsInfo.setCount(toolsInfo.getCount() + 1);
        toolsInfoMananager.updateOne(toolsInfo);


        JSONObject stringObjectHashMap = new JSONObject();

        SystemLoginDTO systemLoginDTO = LoginConstant.systemLoginDTO;
        WMSLoginDTO wmsLoginDTO = LoginConstant.wmsLoginDTO;
        /**
         *  [
         *     {"productSku":"OEMGOODS22101001000014","quantity":"2","productType":"OEM"},
         *     {"productSku":"d84fb55e0b5b0accccc000c9d9e76093","quantity":"2","productType":"normal"},
         *     {"productSku":"41b783f0ed2b1d9afde00cf989ba7615","quantity":"2","productType":"normal"},
         *     {"productSku":"SET22081711000006","quantity":"5","productType":"combination"}
         *   ]
         */

        String username = createOrderDTO.getUserName();
        String password = createOrderDTO.getPassword();
        Integer platform = createOrderDTO.getPlatform();
        Integer orderType = createOrderDTO.getOrderType();
        Integer operationNode = createOrderDTO.getOperationNode();

        ClientLoginDTO clientLoginDTO = clientLoginService.login(username, password);

        //判断平台
        if (!clientLoginDTO.getSystemSource().equals(platform.toString())) {
            clientLoginService.changeLogin(clientLoginDTO);
        }
        //判断订单类型
        if (2 == platform) {
            orderType = OrderType.STOCK.getType();
        }

        List<OrderProductDTO> products = createOrderDTO.getProducts();
        JSONArray stock2B = new JSONArray();
        for (int i = 0; i < products.size(); i++) {
            JSONObject object = new JSONObject();
            OrderProductDTO orderProductDTO = products.get(i);
            Integer productType = orderProductDTO.getProductType();
            if (productType == 1) {
                object.put("productType", "normal");
            } else if (productType == 2) {
                object.put("productType", "OEM");
            } else {
                object.put("productType", "combination");
            }
            object.put("quantity", orderProductDTO.getQuantity());
            object.put("productSku", orderProductDTO.getProductSku());
            stock2B.add(object);
        }

        // 执行下单
        String mixtureCreateOrderProcess = mixtureOrderService.mixtureCreateOrderProcess(clientLoginDTO, stock2B, orderType);
        JSONObject object = JsonUtil.strToJSONObject(mixtureCreateOrderProcess);
        JSONObject data = object.getJSONArray("data").getJSONObject(0);
        CreateOrderResponse createOrderResponse = FastUtil.toBean(data, CreateOrderResponse.class);
        stringObjectHashMap.put("platformData", createOrderResponse);

        String platformOrderNo = createOrderResponse.getPlatformOrderNo();

        if (operationNode == null || operationNode == 0 || operationNode == 1) {
            return SniffResponse.pass(stringObjectHashMap);
        }

        ToolsUtil.sleep(5000);
        String s = purchaseService.allotAutoOrder(systemLoginDTO, platformOrderNo);
        if(2 == operationNode) {
            JSONObject jsonObject = JsonUtil.strToJSONObject(s);
            stringObjectHashMap.put("allotData", jsonObject.getJSONArray("data"));
            return SniffResponse.pass(stringObjectHashMap);
        }

        // 执行采购
        String result = purchaseAllotOrder.getPurchaseOrderNo(platformOrderNo);
        if (StringUtils.isEmpty(result)){

            purchaseService.allotAutoOrder(LoginConstant.systemLoginDTO, platformOrderNo);
            result = purchaseAllotOrder.getPurchaseOrderNo(platformOrderNo);

            if (StringUtils.isEmpty(result)) {
                return SniffResponse.fail(10001, "没有查到对应的采购单号！！！");
            }
        }
        JSONObject purchaseData = JSON.parseObject(result);
        JSONArray purchaseNos = purchaseData.getJSONArray("purchaseNo");
        JSONArray purchaseInfos = new JSONArray();

        //标识已提交采购异常
        Boolean flag = Boolean.TRUE;
        for (int i = 0; i < purchaseNos.size(); i++) {

            JSONObject purchaseInfo =  new JSONObject();
            String purchaseNo = purchaseNos.getString(i);
            purchaseInfo.put("purchaseNo", purchaseNo);
            if (purchaseNo.contains("DHCGD")) {
                oemPurchaseService.oemPurchaseProcess(systemLoginDTO, purchaseNo);
                Object logisticsNumber = ToolsUtil.getStringBuild("oemLogisticsNumber");
                purchaseInfo.put("logisticsNumber", logisticsNumber);
            }
            if (purchaseNo.contains("XSCGD") || purchaseNo.contains("XXCGD")) {
                if(flag) {
                    purchaseAbnormalService.userConfirmProduct(systemLoginDTO,purchaseNo, PurchaseAbnormalType.PURCHASE_ABNORMAL_TYPE1);
                    abnormalOrderService.orderAbnormalProcess(clientLoginDTO, platformOrderNo, CustomerOperateType.CANCEL_PRODUCT);
                    flag = false;
                }else {
                    purchaseService.puchasePrecess(systemLoginDTO, purchaseNo);
                }

                Object logisticsNumber = ToolsUtil.getStringBuild("logisticsNumber");
                purchaseInfo.put("logisticsNumber", logisticsNumber);
            }
            if (purchaseNo.contains("DKCGD")) {
                purchaseService.puchasePrecess(systemLoginDTO, purchaseNo);
                purchaseInfo.put("logisticsNumber", purchaseNo);
            }
            purchaseInfos.add(purchaseInfo);
        }
        stringObjectHashMap.put("purchaseData", purchaseInfos);
        if (operationNode == 3) {
            return SniffResponse.pass(stringObjectHashMap);
        }

        // 执行入库
        wmsStorageService.storageProcess(LoginConstant.wmsLoginDTO, platformOrderNo);
        if (operationNode == 4) {
            return SniffResponse.pass(stringObjectHashMap);
        }


        if (operationNode == 5) {

            Long isCombinationPackTime = 3*60*1000L;
            while( isCombinationPackTime > 0){
                Long sleepTime = 30*1000L;

                List<JSONObject> select = DBUtil.select("WMS-查询组合任务", new ContentDTO("", platformOrderNo));
                if(select.isEmpty()){
                    ToolsUtil.sleep(sleepTime);
                }else {
                    break;
                }
                isCombinationPackTime -= sleepTime;
            }

            if(isCombinationPackTime <= 0){
                stringObjectHashMap.put("message", "查询组合任务超时3分钟，请手动掉接口执行完成组合任务");
                return SniffResponse.pass(stringObjectHashMap);
            }

            // 组合商品执行组合完成
            wmsCombinationOperationService.platformOrderCombinationProcess(wmsLoginDTO, platformOrderNo);
            stringObjectHashMap.put("message", "组合任务完成！！");
            return SniffResponse.pass(stringObjectHashMap);
        }

        return SniffResponse.pass(stringObjectHashMap);
    }

    @ApiOperation("订单一键执行到指定节点")
    @PostMapping("/orderProcess")
    @ApiOperationSupport(order = 10)
    @ApiImplicitParams({@ApiImplicitParam(paramType = "String",name = "platformOrderNo",value = "平台订单号",required = true),
            @ApiImplicitParam(paramType = "Integer",name = "operationNode",value = "2 分单完成; 3 采购完成; 4 入库上架完成; 5 组合完成入库; 6 审单完成; 7 国际发货单待处理; 8 拣货完成; 9 打包完成; 10 发货完成",required = true)})

    public SniffResponse<JSONObject> orderProcess(String platformOrderNo, Integer operationNode) {

        ToolsInfo toolsInfo = toolsInfoMananager.selectOne(30L);
        toolsInfo.setCount(toolsInfo.getCount() + 1);
        toolsInfoMananager.updateOne(toolsInfo);

        JSONObject data = orderService.orderProcess(platformOrderNo, operationNode);

        return SniffResponse.pass(data);
    }

    /**
     * 订单类型
     */
    @RequestMapping(value = "/orderType", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result orderType(HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("1", "直发订单");
        map.put("2", "囤货订单");
        return Result.Success(map);
    }

    /**
     * 订单状态 operationNode（1 下单完成; 2 分单完成; 3 采购完成; 4 入库上架完成; 5 组合完成入库; 6 发货完成）
     */
    @RequestMapping(value = "/operationNode", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result operationNode(HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("1", "下单完成");
        map.put("2", "分单完成");
        map.put("3", "采购完成");
        map.put("4", "入库上架完成");
        map.put("5", "组合完成入库");
        map.put("6", "发货完成");
        return Result.Success(map);
    }

    /**
     * productType（1 普通，2 OEM，3 组合）
     */
    @RequestMapping(value = "/productType", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Result productType(HttpServletResponse resp) {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("1", "普通商品");
        map.put("2", "OEM");
        map.put("3", "组合商品");
        return Result.Success(map);
    }
}
